// dict.js - javascript for dictionary dialog windows.
var EXPORTED_SYMBOLS = ["dict"];


var dict = {

    // Invoked every tiem window is opened.
    onLoad: function() {            
        Components.utils.import("chrome://aatel/content/alphabet/alpha.js");
        var givenTerm = window.arguments[0].term;
        this.alphabet = window.arguments[0].alphabet;
        this.map = alpha.alphaMap[this.alphabet];
        this.newTermDict = {};
        var term = document.getElementById("term");
        term.value = givenTerm;

        var menulist        = document.getElementById("alphabet");
        var menupopup       = document.getElementById("alphabet_list");
        var termConverted   = document.getElementById("term_converted");

        dict.switchKeyboard();

        // Add even handlers for alpha list drop-down
        var i = 0;
        for (key in alpha.alphaMap) {
            var menuItem = document.createElement("menuitem"); 
            menuItem.setAttribute("label", key); 
            menupopup.appendChild(menuItem); 

            function switchAlphabet() {
                dict.alphabet = this.label;
                dict.map = alpha.alphaMap[dict.alphabet];
                dict.switchKeyboard();
                var tree = document.getElementById("candidates");
                dict.termHandler.call(term);
            }

            menuItem.addEventListener("command", switchAlphabet, true);

            if (key == dict.alphabet) {
                menulist.selectedIndex = i;
            }
            i++;
        }
        var addButton = document.getElementById("add");
        addButton.addEventListener("command", dict.addHandler, true);
        var deleteButton = document.getElementById("delete");
        deleteButton.addEventListener("command", dict.deleteHandler, true);

        var upArrow = document.getElementById("up_arrow");
        upArrow.addEventListener("command", dict.upArrowHandler, true);
        var downArrow = document.getElementById("down_arrow");
        downArrow.addEventListener("command", dict.downArrowHandler, true);

        var arpabetBox = document.getElementById("arpabet");
        arpabetBox.addEventListener("input", dict.arpabetHandler, true);
        term.addEventListener("input", dict.termHandler, true);
        dict.termHandler.call(term);
    },


    addHandler: function() {
        var term = document.getElementById("term");
        var arpabetBox = document.getElementById("arpabet");

        var tree = document.getElementById("candidates");
        if (!dict.candidates) dict.candidates = [];
        dict.candidates.unshift(arpabetBox.value.split(','));
        dict.newTermDict[term.value.toUpperCase()] = dict.candidates;
        dict.updateTree(dict.candidates);
    },


    deleteHandler: function() {
        var term = document.getElementById("term");
        var tree = document.getElementById("candidates");
        var pos = tree.currentIndex;
        dict.candidates.splice(pos, 1);
        dict.updateTree(dict.candidates);
    },


    upArrowHandler: function() {
        var term = document.getElementById("term");
        var tree = document.getElementById("candidates");
        var pos = tree.currentIndex;
        if (pos == 0) return;
        var tmp = dict.candidates[pos-1];
        dict.candidates[pos-1] = dict.candidates[pos];
        dict.candidates[pos] = tmp;
        dict.updateTree(dict.candidates);
        tree.view.selection.select(pos-1);
    },


    downArrowHandler: function() {
        var term = document.getElementById("term");
        var tree = document.getElementById("candidates");
        var pos = tree.currentIndex;
        if (pos == dict.candidates.length-1) return;
        var tmp = dict.candidates[pos+1];
        dict.candidates[pos+1] = dict.candidates[pos];
        dict.candidates[pos] = tmp;
        dict.updateTree(dict.candidates);
        tree.view.selection.select(pos+1);
    },


    termHandler: function() {
        var keyboard        = document.getElementById("keyboard");
        var termConverted   = document.getElementById("term_converted");
        var arpabet         = document.getElementById("arpabet");

        arpabet.value = alpha.latinPhonemes(this.value, dict.map);
        dict.arpabetHandler.call(arpabet);
        dict.candidates = alpha.lookup(this.value, dict.newTermDict);
        if (!dict.candidates) dict.candidates = [];
        dict.updateTree();
    },


    arpabetHandler: function() {
        var cursor = this.selectionEnd;    // save cursor postion
        this.value = this.value.toUpperCase();
        this.value = this.value.replace(' ',',');
        var termConverted = document.getElementById("term_converted");
        if (this.value == "") termConverted.value = "";
        var phonetic = alpha.transWord(this.value.split(','), dict.map);
        if (phonetic != "INVALID") {
            termConverted.value = phonetic;
        }
        this.selectionEnd = cursor;
    },


    updateTree: function() {

        // Update tree for displaying candidates.
        var treeView = {  
            setTree: function(treebox)                  { this.treebox = treebox; },  
            isContainer: function(row)                  { return false; },  
            isSeparator: function(row)                  { return false; },  
            isSorted: function()                        { return false; },  
            getLevel: function(row)                     { return 0; },  
            getImageSrc: function(row,col)              { return null; },  
            getRowProperties: function(row,props)       {},  
            getColumnProperties: function(col,props)    {}, 
            getCellProperties: function(row,col,props) {
                if (col.id == "transliteration") {
                    var aserv=Components.classes["@mozilla.org/atom-service;1"].getService(Components.interfaces.nsIAtomService);
                    props.AppendElement(aserv.getAtom("transColCell"));
                }
            },  

            getCellText : function(row,column){  
                if (column.id == "priority") {
                    return row + 1;
                }
                else if (column.id == "arpabet") {
                    return dict.candidates[row];
                }
                else if (column.id == "transliteration") {
                    return alpha.transWord(dict.candidates[row], dict.map, 0);
                }
            },
            rowCount : dict.candidates.length  
        };  
        
        var tree = document.getElementById("candidates");
        tree.view = treeView;

    },


    switchKeyboard: function() {
        var keyboard        = document.getElementById("keyboard");
        var termConverted   = document.getElementById("term_converted");
        var arpabet         = document.getElementById("arpabet");
        var reverseMap      = alpha.reverseCharacterMap(dict.map);

        termConverted.value = alpha.transWord(arpabet.value.split(','), dict.map);
        
        while (keyboard.hasChildNodes()) { 
            keyboard.removeChild(keyboard.lastChild); 
        } 

        for (var i = dict.map.unicodeStart; i <= dict.map.unicodeEnd; i++) {
            var glyph = alpha.unicode(i);
            var button = document.createElement("button"); 
            button.setAttribute("id", glyph); 
            button.setAttribute("label", glyph); 
            button.setAttribute("class", "thinbutton"); 
            
            // Append phoneme to arpabet textbox and use the contents of
            // the arpabaet textbox to determine termConverted.
            button.addEventListener("command", function() {
                var ph = alpha.altPhonemes(this.label, reverseMap);
                if (arpabet.value) {
                    arpabet.value = arpabet.value.split(',').concat(ph);
                }
                else {
                    arpabet.value = [ph];
                }
                termConverted.value = alpha.transWord(arpabet.value.split(','), dict.map);
            }, true);
            keyboard.appendChild(button); 
        }
    },


    saveChanges: function() {
        function extend(destination, source) {
            for (var property in source) {
                if (source.hasOwnProperty(property)) {
                    destination[property] = source[property];
                }
            }
            return destination;
        };
        alpha.userDict = extend(alpha.userDict, dict.newTermDict);
        dict.newTermDict = {};
        alpha.writeDictionary(alpha.userDict);
    }

}

